<template>
  <SeachTable @handleSelectionChange="handleSelectionChange" class="mySeachTable" :tableSelection="tableSelection"
    :tableType="1" ref="seachTableRef" :forms="tableForms" :btnLefts="btnLefts" :tableLoading="tableLoading"
    :tableConfig="tableConfig" :reserveSelection="true" rowKey="id" :tableData="tableData" :totalPage="totalPage" @handlerSearch="handlerSearch">
    <template #storeSalesStatusHeader>
      <div class="flex align-items-center">
        <span>门店销售状态</span>
        <el-tooltip class="box-item" effect="dark" placement="top-end">
          <el-image :src="warningCircle" style="margin-left: 4px;width: 14px;height: 14px;"></el-image>
          <template #content>
            <div style="width: 216px;font-size: 14px;">
              正常：门店在{{itemDetail.mallInfoPut === 1 ? '线上、':''}}线下可正常销售该产品
            </div>
            <div style="width: 216px;font-size: 14px;">
              停售：门店在{{itemDetail.mallInfoPut === 1 ? '线上、':''}}线下不能对外销售该产品
            </div>
          </template>
        </el-tooltip>
      </div>
    </template>
    <template #storeSalesStatus="{ row }">
      <span>{{ row.saleState === 1 ? '正常' : '停售' }}</span>
    </template>
  </SeachTable>
</template>

<script setup>
import { changeOptions } from '@/utils/common'
import { useDimensionality } from './hooks';
import { useConfirm } from '@/hooks/index'
import warningCircle from '@/assets/icon/warning-circle.png'
import { getStoreDim,updateSaleStatus } from '@/api/BusinessScope/commodityControl'

// 经营品牌
const { brandList,storeGrouping,itemDetail } = useDimensionality()
watch(itemDetail,(newVal)=>{
  if(newVal.id){
    seachTableRef.value.initSearch()
  }
},{deep:true})

const seachTableRef = ref(null)
const clearSelection = () => {
  seachTableRef.value && seachTableRef.value.table.clearSelection()
}
const tableSelection = ref(false)
const tableLoading = ref(false)
const tableData = ref([])
const totalPage = ref(0)

const handlerSearch = async (data) => {
  try{
    if(!itemDetail.value.id) return
    tableLoading.value = true
    const res = await getStoreDim({
      ...data,
      baseId:itemDetail.value.id,
      classify:itemDetail.value.classify
    })
    tableData.value = res.records
    totalPage.value = res.total
  }finally{
    tableLoading.value = false
  }
}
const batchIds = ref([])
const handleSelectionChange = (val) => {
  batchIds.value = val
}

const action1 = ref(true)
const action2 = ref(true)

const batchOperation = (isDisable,row={},) => {
  if(!row.id && !batchIds.value.length)return
  let text = isDisable ? '停售' : '恢复销售'
  text = row.id ? text : `批量${text}`
  ElMessageBox.confirm(`确定要${text}吗？`, '提示', {
    type: 'warning',
    beforeClose: async (action, instance, done) => {
      const params = {
        saleStateDTOS:[]
      }
      if(row?.id){
        params.saleStateDTOS = [{
          storeId:row.id,
          enterpriseId:row.enterpriseId,
          baseId:itemDetail.value.id,
          classify:itemDetail.value.classify,
          saleStatus:isDisable ? 2 : 1
        }]
      }else{
        params.saleStateDTOS = batchIds.value.map(item =>{
          return {
            storeId:item.id,
            enterpriseId:item.enterpriseId,
            baseId:itemDetail.value.id,
            classify:itemDetail.value.classify,
            saleStatus:isDisable? 2 : 1
          }
        })
      }
      const res = await useConfirm(action, instance, done, updateSaleStatus,params)
      if (res) {
        ElMessage.success(`${text}成功`)
        clearSelection()
        seachTableRef.value.handlerSearch()
      }
    },
  })
}
const btnLefts = ref([
  {
    label: '批量停售',
    type: 'danger',
    plain: true,
    show: () => action1.value,
    click: () => {
      if (tableSelection.value) {
        batchOperation(true)
      } else {
        action2.value = false
        tableSelection.value = true
      }
    }
  },
  {
    label: '批量恢复销售',
    type: 'primary',
    plain: true,
    show: () => action2.value,
    click: () => {
      if (!tableSelection.value) {
        action1.value = false
        tableSelection.value = true
      } else {
        batchOperation(false)
      }
    }
  },
  {
    label: '退出操作',
    type: 'default',
    show: () => {
      return !action1.value || !action2.value
    },
    click: () => {
      action1.value = true
      action2.value = true
      tableSelection.value = false
      clearSelection()
    }
  }
])
const tableForms = ref([
  {
    type: 'input',
    prop: "keywords",
    placeholder: "门店名称/ID",
    label: "",
    model: "",
  },
  {
    type: 'input',
    prop: "enterpriseName",
    placeholder: "所属商户",
    label: "",
    model: "",
  },
  {
    type: "select",
    placeholder: "经营方式",
    multiple: true,
    width:200,
    filterable: true,
    label: '',
    prop: 'managementWays',
    data: [{
      value: 1,
      label: '直营',
    },{
      value: 2,
      label: '加盟',
    }],
    model: [],
  },
  {
    type: "select",
    placeholder: "经营品牌",
    width:200,
    multiple: true,
    filterable: true,
    label: '',
    prop: 'brandIds',
    data: [],
    model: [],
  },
  {
    type: 'input',
    prop: "address",
    placeholder: "所属地区",
    label: "",
    model: "",
  },
  {
    type: "select",
    placeholder: "门店分组",
    multiple: true,
    filterable: true,
    label: '',
    prop: 'storeGroupIds',
    data: [],
    model: [],
  },
])
changeOptions(tableForms,['brandIds','storeGroupIds'],[brandList,storeGrouping])
const tableConfig = ref([
  {
    label: '门店ID',
    prop: 'code',
    width: 150,
  },
  {
    label: '营业执照名称',
    prop: 'licenseName',
    width: 200,
  },
  {
    label: '门店名称',
    prop: 'storeName',
    width: 150,
  },
  {
    label: '所属商户',
    prop: 'enterpriseName',
    width: 158,
  },
  {
    label: '经营方式',
    prop: 'managementWay',
    width: 100,
    format:(value)=>{
      return value===1?'直营':'加盟'
    }
  },
  {
    label: '经营品牌',
    prop: 'brandId',
    width: 100,
    format:(value)=>{
      if(!value) return '-'
      const brandIds = value.split(',')
      return brandIds.map(item=>brandList.find(v=>v.value===item)?.label ?? '').filter(item=>item).join(',') || '-'
    }
  },
  {
    label: '所属地区',
    prop: 'addr',
    width: 158,
  },
  {
    label: '门店分组',
    prop: 'storeGroupId',
    width: 100,
    format:(value)=>{
      if(!value) return '-'
      const storeGroupIds = value.split(',')
      return storeGroupIds.map(item=>storeGrouping.find(v=>v.value===item)?.label?? '').filter(item=>item).join(',') || '-'
    }
  },
  {
    type: 'slot',
    label: '门店销售状态',
    prop: 'saleState',
    width: 140,
    needHeader: true,
    slotHeaderName: 'storeSalesStatusHeader',
    slotName: 'storeSalesStatus'
  },
  {
    type: "action",
    label: '操作',
    prop: 'name',
    fixed: "right",
    width: 130,
    btns: [
      {
        label: () => '立即停售',
        type: 'danger',
        show: (row) => row.saleState === 1,
        click: (row) => {
          console.log('立即停售', row)
          batchOperation(true,row)
        }
      },
      {
        label: () => '恢复销售',
        type: 'primary',
        show: (row) => row.saleState === 2,
        click: (row) => {
          console.log('立即停售', row)
          batchOperation(false,row)
        }
      }
    ]
  }
])

</script>

<style lang="less" scoped>
div{
  box-sizing: border-box;
}
.mySeachTable {
  background-color: #fff;
  width: calc(100% - 316px) !important;
}
</style>